Popular Searches
Popular Course Categories
Popular Courses

Defining Fields and Methods in Classes

Defining Fields and Methods in Classes

Object-Oriented Programming Fundamentals

Defining Fields and Methods in Classes in Java

Course: Core Java Training

Topic: Defining Fields and Methods in Classes

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Fields and Methods in Java

In Java, a class is a blueprint used to create objects. It defines the data an object stores and the operations it can perform. Two fundamental components of a class are fields and methods.

Fields represent the data or properties of an object, while methods define the behavior or actions that an object can perform. Together, they help developers organize related data and functionality into a single reusable structure.

For example, a Student class may contain fields such as name, rollNumber, and marks, along with methods such as displayDetails(), calculateGrade(), and updateMarks().

class Student {
    String name;
    int rollNumber;
    double marks;

    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
        System.out.println("Marks: " + marks);
    }
}

In this example, name, rollNumber, and marks are fields. The displayDetails() method defines an operation that displays the student's information.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the purpose of fields and methods in Java classes.
  • Declare fields using appropriate data types and access modifiers.
  • Define instance fields, static fields, and constants.
  • Create methods with parameters, return types, and method bodies.
  • Understand the difference between instance methods and static methods.
  • Access fields and invoke methods using objects.
  • Apply encapsulation and basic object-oriented programming principles.
  • Write reusable Java classes for practical applications.

3. What Are Fields in Java?

A field is a variable declared inside a class but outside its methods, constructors, and initialization blocks. Fields store information associated with a class or its objects.

Fields are also commonly called member variables or class-level variables, depending on their type and context.

3.1 Syntax for Declaring a Field

dataType fieldName;

A field declaration can also include an access modifier, a keyword such as static or final, and an initial value.

private String studentName;
public int age;
static int studentCount;
final double PI = 3.14159;

Here, studentName is a private instance field, age is a public instance field, studentCount is a static field, and PI is a final field.

3.2 Components of a Field Declaration

Component Description Example
Access modifier Controls visibility. private, public
Data type Specifies the type of value stored. int, String, double
Field name Identifies the variable. studentName
Initializer Assigns an initial value. int age = 20;
static keyword Makes the field belong to the class. static int count;
final keyword Prevents reassignment after initialization. final int MAX = 100;

4. Types of Fields in Java

4.1 Instance Fields

Instance fields belong to individual objects. Each object normally has its own separate value for every instance field.

class Employee {
    String name;
    double salary;
}

class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        e1.name = "Amit";
        e1.salary = 40000;

        e2.name = "Priya";
        e2.salary = 50000;

        System.out.println(e1.name);
        System.out.println(e2.name);
    }
}

Output:

Amit
Priya

Both Employee objects have separate name and salary values. Updating one object's instance field does not automatically update the corresponding field in another object.

4.2 Static Fields

A static field belongs to the class rather than to each individual object. All instances of that class share the same static field.

class Employee {
    static String company = "Tech Solutions";
    String name;
}

class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        e1.name = "Amit";
        e2.name = "Priya";

        System.out.println(Employee.company);
        System.out.println(e1.name);
        System.out.println(e2.name);
    }
}

Output:

Tech Solutions
Amit
Priya

Static fields are commonly used for shared configuration, counters, and values that logically belong to the class. Accessing them through the class name is generally preferred.

4.3 Final Fields and Constants

A final field can be assigned only once. After it has been initialized, it cannot be reassigned. A final reference prevents the reference from pointing to a different object, although the referenced object's internal state may still be mutable.

class Product {
    final int productId = 101;
    static final double TAX_RATE = 0.18;
}

In this example, productId cannot be reassigned after initialization, and TAX_RATE represents a class-level constant. Constant names are conventionally written in uppercase with underscores between words.

5. Default Values of Fields

Java automatically assigns default values to fields when an object is created or when a class is initialized. Local variables declared inside methods do not receive these default values and must be initialized before they are read.

Field Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Reference types null
class Example {
    int number;
    boolean active;
    String message;
}

class Main {
    public static void main(String[] args) {
        Example obj = new Example();

        System.out.println(obj.number);
        System.out.println(obj.active);
        System.out.println(obj.message);
    }
}

Output:

0
false
null

6. What Are Methods in Java?

A method is a named block of code defined inside a class that performs a specific task. Methods allow developers to divide complex programs into smaller, manageable, and reusable units.

A method may receive input through parameters, perform calculations or other operations, and return a result. A method declared with the void return type does not return a value to its caller.

6.1 Syntax for Defining a Method

accessModifier returnType methodName(parameters) {
    // Method body
}

For example:

public int add(int a, int b) {
    return a + b;
}

This method accepts two integer parameters and returns their sum.

6.2 Components of a Method

Component Meaning Example
Access modifier Defines accessibility. public
Return type Specifies the result type. int, String, void
Method name Identifies the method. add
Parameters Receive input values. int a, int b
Method body Contains executable statements. return a + b;
Return statement Sends a result to the caller when required. return result;

7. Types of Methods in Java

7.1 Instance Methods

Instance methods are associated with objects. They can directly access instance fields and other accessible instance methods through the current object.

class Rectangle {
    double length;
    double width;

    double calculateArea() {
        return length * width;
    }
}

class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();

        rectangle.length = 10;
        rectangle.width = 5;

        System.out.println(rectangle.calculateArea());
    }
}

Output:

50.0

The calculateArea() method uses the object's length and width fields to calculate the area.

7.2 Static Methods

Static methods belong to the class and can be called using the class name without creating an object. They cannot directly access instance fields or call instance methods without an object reference.

class Calculator {
    static int multiply(int a, int b) {
        return a * b;
    }
}

class Main {
    public static void main(String[] args) {
        int result = Calculator.multiply(5, 4);
        System.out.println(result);
    }
}

Output:

20

Static methods are useful for utility operations that do not depend on the state of a particular object.

7.3 Methods with Parameters

Parameters allow a method to receive information from its caller. The values supplied when calling the method are called arguments.

class Greeting {
    void greet(String name) {
        System.out.println("Hello, " + name);
    }
}

class Main {
    public static void main(String[] args) {
        Greeting greeting = new Greeting();
        greeting.greet("Rahul");
    }
}

Output:

Hello, Rahul

7.4 Methods with Return Values

A method can return a calculated result or another value to its caller. The returned value must be compatible with the declared return type.

class Calculator {
    double calculateAverage(double a, double b) {
        return (a + b) / 2.0;
    }
}

The method returns a double value representing the average of two numbers.

7.5 Void Methods

A void method performs an operation without returning a value. It can display information, update fields, or execute other tasks.

class Message {
    void display() {
        System.out.println("Welcome to Java");
    }
}

A void method can use a plain return statement to exit early, but it cannot return a value.

8. Defining Fields and Methods Together

Fields describe an object's state, while methods define the behavior that works with that state. Combining them inside a class makes programs easier to understand and maintain.

class BankAccount {
    String accountHolder;
    double balance;

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }

        return false;
    }

    void displayBalance() {
        System.out.println("Account Holder: " + accountHolder);
        System.out.println("Balance: " + balance);
    }
}

class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();

        account.accountHolder = "Anita";
        account.balance = 1000;

        account.deposit(500);
        account.withdraw(200);
        account.displayBalance();
    }
}

Output:

Account Holder: Anita
Balance: 1300.0

This example illustrates how methods operate on the fields of a BankAccount object. The deposit() method adds a valid amount, while withdraw() checks the balance before deducting money.

9. Accessing Fields and Calling Methods

For accessible instance members, Java uses an object reference followed by the dot operator to access a field or call a method.

objectName.fieldName;
objectName.methodName();

Example:

class Car {
    String brand;

    void start() {
        System.out.println(brand + " is starting");
    }
}

class Main {
    public static void main(String[] args) {
        Car car = new Car();

        car.brand = "Toyota";
        car.start();
    }
}

Output:

Toyota is starting

Static members should generally be accessed through the class name, for example, Calculator.multiply(5, 4).

10. Using Constructors to Initialize Fields

A constructor is a special class member that runs when an object is created. It has the same name as the class and does not declare a return type. Constructors are often used to initialize fields with meaningful values.

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println(name + " is " + age + " years old");
    }
}

class Main {
    public static void main(String[] args) {
        Student student = new Student("Neha", 21);
        student.display();
    }
}

Output:

Neha is 21 years old

The this keyword refers to the current object. In this example, this.name refers to the field, while name refers to the constructor parameter. This distinction makes initialization clear.

11. Encapsulation and Access Modifiers

Encapsulation is an object-oriented programming principle that combines data and behavior within a class while controlling how the internal state is accessed or modified.

Instead of exposing fields directly, developers commonly declare them private and provide public methods to validate and manage changes.

Modifier Accessibility
private Accessible within the declaring class.
Default (package-private) Accessible within the same package.
protected Accessible within the same package and through permitted subclass access.
public Accessible wherever the declaring type and other applicable access rules permit.

11.1 Example of Encapsulation

class Employee {
    private double salary;

    public void setSalary(double salary) {
        if (salary >= 0) {
            this.salary = salary;
        }
    }

    public double getSalary() {
        return salary;
    }
}

class Main {
    public static void main(String[] args) {
        Employee employee = new Employee();

        employee.setSalary(45000);
        System.out.println(employee.getSalary());
    }
}

Output:

45000.0

The private salary field cannot be accessed directly from Main. The setter validates the value before updating the field, and the getter provides controlled access to it.

12. Difference Between Fields and Local Variables

Feature Fields Local Variables
Declaration location Inside a class but outside methods and constructors. Inside a method, constructor, or block.
Lifetime Depends on whether they are instance or static fields. Generally limited to the execution of the enclosing scope.
Default values Receive default values. Must be definitely assigned before use.
Access Controlled by field modifiers and scope. Limited by lexical scope.
Purpose Store object or class state. Store temporary values during execution.

13. Difference Between Instance and Static Members

Feature Instance Field or Method Static Field or Method
Association Associated with an object. Associated with a class.
Storage or state Each object has its own instance state. Static fields are shared at the class level.
Access Usually through an object reference. Usually through the class name.
Instance field access Can access instance fields directly. Cannot directly access instance fields without an object.
Typical use Object-specific data and behavior. Shared data and utility operations.

14. Best Practices for Defining Fields and Methods

  • Choose meaningful field and method names that explain their purpose.
  • Use camelCase for fields and methods, such as employeeName and calculateTotal().
  • Use PascalCase for class names, such as EmployeeRecord.
  • Declare fields private by default when direct external access is unnecessary.
  • Use constructors to initialize objects in a valid state.
  • Validate input before modifying important fields.
  • Keep methods focused on one clear responsibility.
  • Use static members only when the behavior or data logically belongs to the class.
  • Use final for values or references that must not be reassigned.
  • Avoid creating unnecessary getter and setter methods when they do not support a meaningful design requirement.
  • Document complex methods and important business rules with clear comments.
  • Use consistent formatting and indentation to improve readability.

15. Common Mistakes and Troubleshooting

Mistake Why It Happens Solution
Calling an instance method from a static context The method requires an object. Create an object or redesign the method as static if appropriate.
Accessing a private field directly The field is restricted to its declaring class. Use an appropriate public method or another controlled interface.
Using a local variable before initialization Java requires local variables to be definitely assigned. Assign a value before reading the variable.
Using an incorrect return type The returned expression is incompatible with the declared type. Return a compatible value or correct the return type.
Confusing a field with a parameter Both variables use the same name. Use this.fieldName to refer to the current object's field.
Creating an invalid object state Fields accept inappropriate values. Use constructors, validation, and controlled methods.
Changing shared static state unintentionally All objects use the same static field. Use instance fields for object-specific data.

16. Practical Exercise: Create a Product Class

Create a Product class with fields for productId, productName, price, and quantity. Add methods to calculate the total inventory value, update the quantity, and display product details.

Sample Solution

class Product {
    private int productId;
    private String productName;
    private double price;
    private int quantity;

    Product(int productId, String productName,
            double price, int quantity) {
        this.productId = productId;
        this.productName = productName;
        setPrice(price);
        setQuantity(quantity);
    }

    public void setPrice(double price) {
        if (price >= 0) {
            this.price = price;
        }
    }

    public void setQuantity(int quantity) {
        if (quantity >= 0) {
            this.quantity = quantity;
        }
    }

    public double calculateInventoryValue() {
        return price * quantity;
    }

    public void displayDetails() {
        System.out.println("Product ID: " + productId);
        System.out.println("Product Name: " + productName);
        System.out.println("Price: " + price);
        System.out.println("Quantity: " + quantity);
        System.out.println("Inventory Value: "
                + calculateInventoryValue());
    }
}

class Main {
    public static void main(String[] args) {
        Product product =
                new Product(101, "Keyboard", 800, 10);

        product.displayDetails();
    }
}

Expected Output:

Product ID: 101
Product Name: Keyboard
Price: 800.0
Quantity: 10
Inventory Value: 8000.0

Exercise extensions:

  • Add a method that applies a discount to the product price.
  • Add a method to increase stock after a delivery.
  • Prevent negative prices and quantities.
  • Create multiple Product objects and compare their inventory values.

17. Interview Questions and Answers

Q1. What is a field in Java?

A field is a variable declared within a class but outside methods and constructors. It stores state associated with an object or class.

Q2. What is a method in Java?

A method is a named block of code that performs a task. It can accept parameters and may return a value.

Q3. What is the difference between a field and a method?

A field stores data, whereas a method defines behavior or operations that can work with that data.

Q4. What is an instance field?

An instance field belongs to an object. Each object generally maintains its own value for that field.

Q5. What is a static field?

A static field belongs to the class and is shared among its instances.

Q6. Can a static method access an instance field directly?

No. A static method needs an object reference to access an instance field because the field belongs to an object.

Q7. What is the purpose of the this keyword?

The this keyword refers to the current object. It is frequently used to distinguish instance fields from parameters with the same names.

Q8. What is a return type?

A return type specifies the type of value a method returns. The void keyword indicates that a method does not return a value.

Q9. Why should fields often be private?

Private fields help protect an object's internal state and allow controlled access through methods that can validate data.

Q10. What is the difference between a constructor and a method?

A constructor initializes a newly created object and has the class name without a return type. A method performs an operation and has a declared return type, including void.

Q11. Can a class contain multiple methods?

Yes. A class can contain multiple methods, each performing a different operation. Methods may also be overloaded when their parameter lists differ.

Q12. What happens if a field is not explicitly initialized?

Java assigns the field its type's default value. For example, an int field defaults to 0, a boolean field to false, and a reference field to null.

18. Quick Revision Checklist

  • Fields store the state of objects or classes.
  • Instance fields maintain object-specific values.
  • Static fields represent shared class-level data.
  • Final fields cannot be reassigned after initialization.
  • Methods define operations that objects or classes can perform.
  • Parameters pass information into methods.
  • Return types specify the kind of result a method provides.
  • Static methods can be called using the class name.
  • The this keyword refers to the current object.
  • Constructors help initialize fields when objects are created.
  • Encapsulation protects data through controlled access.
  • Meaningful names, validation, and focused methods improve code quality.

19. Conclusion

Defining fields and methods is a fundamental skill in Core Java programming. Fields store the state of objects and classes, while methods define the operations performed on that state. Understanding instance and static members, method parameters, return types, constructors, and access modifiers helps developers create structured and reusable applications.

Practicing these concepts through classes such as Student, Employee, BankAccount, Rectangle, and Product builds a strong foundation for object-oriented programming, inheritance, polymorphism, abstraction, and other advanced Java topics.


Learn More with JustAcademy

Strengthen your Java programming fundamentals through structured learning and practical exercises.

Explore the Core Java Training Course

Register for a Course Demo

Visit the JustAcademy Website

whatsapp